package com.lz.dubbo.producer.common.utils.ftp;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.IOException;
import java.io.InputStream;

public class FtpUtil {

    public boolean uploadFile(String hostname, Integer port, String username, String password,
                              String filePath, String fileName, InputStream inputStream) throws Exception {
        FTPClient ftpClient = initFtpClient(hostname, port, username, password);
        return this.uploadFile(ftpClient, filePath, fileName, inputStream);
    }

    private FTPClient initFtpClient(String hostname, Integer port, String username, String password) throws Exception {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        try {
            ftpClient.connect(hostname, port);
            ftpClient.login(username, password);
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                throw new Exception("ftp服务器连接失败");
            } else {
//                logger.info("connect successfu...ftp服务器:" + hostname + ":" + port);
            }
        } catch (Exception e) {
            throw e;
        }
        return ftpClient;
    }

    private boolean uploadFile(FTPClient ftpClient, String filePath, String fileName, InputStream inputStream) {
        boolean flag = false;
        try {
//            logger.info("开始上传文件");
            ftpClient.makeDirectory(filePath);
            ftpClient.changeWorkingDirectory(filePath);
            ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            ftpClient.logout();
            flag = true;
//            logger.info("上传文件成功");
        } catch (Exception e) {
//            logger.info("上传文件失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }
}
